package com.kmproject.haifu.mvp.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.widget.CustomPopupWindow;
import com.jess.arms.widget.alertview.AlertView;
import com.jess.arms.widget.alertview.AlertViewOnItemClickListener;
import com.jess.arms.widget.autolayout.AutoToolbar;
import com.kmproject.haifu.R;
import com.kmproject.haifu.app.AppConstant;
import com.kmproject.haifu.app.hfinterface.AliYunDunCheckInterface;
import com.kmproject.haifu.app.hfinterface.WebViewCheakInterface;
import com.kmproject.haifu.app.utils.PwdCheckUtil;
import com.kmproject.haifu.di.component.DaggerUserRegistComponent;
import com.kmproject.haifu.mvp.contract.UserRegistContract;
import com.kmproject.haifu.mvp.model.api.Api;
import com.kmproject.haifu.mvp.model.entity.beans.VerificationBean;
import com.kmproject.haifu.mvp.model.entity.resbean.H5CheckCodeBean;
import com.kmproject.haifu.mvp.presenter.UserRegistPresenter;
import com.xw.repo.XEditText;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cc.ibooker.zcountdownviewlib.SingleCountDownView;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 06/22/2019 16:48
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class UserRegistActivity extends BaseActivity<UserRegistPresenter> implements UserRegistContract.View {

    @BindView(R.id.toolbar_back)
    RelativeLayout toolbarBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.back_right_icon)
    ImageView backRightIcon;
    @BindView(R.id.back_right_txt)
    TextView backRightTxt;
    @BindView(R.id.toolbar_right)
    RelativeLayout toolbarRight;
    @BindView(R.id.toolbar)
    AutoToolbar toolbar;
    @BindView(R.id.user_phone_Attribution_txt)
    TextView userPhoneAttributionTxt;
    @BindView(R.id.user_phone_Attribution_img)
    ImageView userPhoneAttributionImg;
    @BindView(R.id.user_phone_txt)
    XEditText userPhoneTxt;
    @BindView(R.id.user_pwd_txt)
    XEditText userPwdTxt;
    @BindView(R.id.user_regist_zym_singleCountDownView)
    SingleCountDownView userRegistZymSingleCountDownView;
    @BindView(R.id.user_regist_btn)
    TextView userRegistBtn;
     private boolean isTimefinish=true;
     private  Intent intent;
    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerUserRegistComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_user_regist; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        setYzmBtnStatus(false);
        setBtnStatus(false);
        userPhoneTxt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length()>9)
                {
                    setYzmBtnStatus(true);
                }else {
                    setYzmBtnStatus(false);
                }
                if (!TextUtils.isEmpty(s)&&!TextUtils.isEmpty(userPwdTxt.getText().toString()))
                {
                    setBtnStatus(true);
                }else {
                    setBtnStatus(false);
                }
            }
        });

        userPwdTxt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s)&&!TextUtils.isEmpty(userPhoneTxt.getText().toString())&&userPwdTxt.getText().toString().length()==6)
                {
                    setBtnStatus(true);
                }else {
                    setBtnStatus(false);
                }
            }
        });


       // 单个倒计时结束事件监听
        userRegistZymSingleCountDownView.setSingleCountDownEndListener(new SingleCountDownView.SingleCountDownEndListener() {
            @Override
            public void onSingleCountDownEnd() {
                // 倒计时结束
                isTimefinish=true;
                setYzmBtnStatus(true);
            }
        });
    }

    @Override
    public void showLoading() {
      loadingDialog.show();
    }

    @Override
    public void hideLoading() {
        loadingDialog.dismiss();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.user_phone_Attribution_txt, R.id.user_regist_zym_singleCountDownView, R.id.user_regist_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.user_phone_Attribution_txt:
                showPopuWindow();
                break;
            case R.id.user_phone_Attribution_img:
                showPopuWindow();
                break;
            case R.id.user_regist_zym_singleCountDownView:
                if (!isTimefinish)
                {
                    showMessage("稍后再试");
                    return;
                }
                if (userPhoneAttributionTxt.getText().toString().equals("+63"))
                {
                    if (userPhoneTxt.getText().toString().substring(0,1).equals("0"))
                    {
                        showMessage("手机号不能是0开头");
                        return;
                    }
                    if (!userPhoneTxt.getText().toString().substring(0,1).equals("9"))
                    {
                        showMessage("手机号必须是9开头");
                        return;
                    }
                    if (userPhoneTxt.getText().toString().length()!=10)
                    {
                        showMessage("手机号长度必须是十位");
                        return;
                    }
                }else {
                    if (userPhoneTxt.getText().toString().length()!=11)
                    {
                        showMessage("手机号必须是11位");
                        return;
                    }
                }
                showCheackDialog(this,userPhoneAttributionTxt);
//                PwdCheckUtil.callSDKDoVerification(this, VerifyType.NOCAPTCHA, null, new AliYunDunCheckInterface() {
//                    @Override
//                    public void aliYunDunCheckCallBack(int retInt, Map code) {
//                        switch (retInt) {
//                            case VerifyActivity.VERIFY_SUCC:
//                                Log.e("####", code.toString());
//                               String sessionid = (String) code.get("sessionID");
////                                setLogMessage("验证通过:\nsessionId=" + (String) code.get("sessionID"));
//                                if (userPhoneAttributionTxt.getText().toString().equals("+63"))
//                                {
//                                    mPresenter.queryVerification("63"+userPhoneTxt.getText().toString(),sessionid,AppConstant.ALIYUNDUN_CHECK_APPID);
//                                }else
//                                {
//                                    mPresenter.queryVerification("86"+userPhoneTxt.getText().toString(),sessionid,AppConstant.ALIYUNDUN_CHECK_APPID);
//                                }
//                                break;
//
//                            case VerifyActivity.VERIFY_FAILED:
//                                ArmsUtils.makeText(UserRegistActivity.this,(String) (null != code.get("errorMsg") ? code.get("errorMsg") : ""));
//                                VerifyActivity.finishVerifyUI();
//                                break;
//                        }
//                    }
//                });

                break;
            case R.id.user_regist_btn:
                 intent=new Intent(this,UserResetPwdActivity.class);
                if (userPhoneAttributionTxt.getText().toString().equals("+63"))
                {
                    if (userPhoneTxt.getText().toString().substring(0,1).equals("0"))
                    {
                        showMessage("手机号不能是0开头");
                        return;
                    }
                    if (!userPhoneTxt.getText().toString().substring(0,1).equals("9"))
                    {
                        showMessage("手机号必须是9开头");
                        return;
                    }
                    if (userPhoneTxt.getText().toString().length()!=10)
                    {
                        showMessage("手机号长度必须是十位");
                        return;
                    }
                    intent.putExtra("mobile","63"+userPhoneTxt.getText().toString().trim());
                }else {
                    intent.putExtra("mobile","86"+userPhoneTxt.getText().toString().trim());

                }
               mPresenter.registerNext(intent.getStringExtra("mobile"),userPwdTxt.getText().toString().trim());
                break;
        }
    }

    /**
     * 设置登录按钮状态
     * @param isClick
     */
    public void setBtnStatus(boolean isClick)
    {
        if (isClick)
        {
            userRegistBtn.setEnabled(true);
            userRegistBtn.setBackgroundResource(R.drawable.button_yellow_bg);
            userRegistBtn.setTextColor(getResources().getColor(R.color.color_191919));
        }else {
            userRegistBtn.setEnabled(false);
            userRegistBtn.setBackgroundResource(R.drawable.button_gray_bg);
            userRegistBtn.setTextColor(getResources().getColor(R.color.color_EDEDED));
        }
    }

    /**
     * 设置验证码按钮的状态
     * @param isClick
     */
    public void setYzmBtnStatus(boolean isClick)
    {
        if (userRegistZymSingleCountDownView==null)
        {
            return;
        }
         if (isClick)
         {
             userRegistZymSingleCountDownView.setEnabled(true);
             userRegistZymSingleCountDownView.setTextColor(getResources().getColor(R.color.color_191919));
             userRegistZymSingleCountDownView.setBackgroundResource(R.drawable.box_black_white_bg);
             userRegistZymSingleCountDownView.setText(getResources().getString(R.string.user_requery_yzm));
         }else {
             userRegistZymSingleCountDownView.setEnabled(false);
             userRegistZymSingleCountDownView.setTextColor(getResources().getColor(R.color.color_C6C6C6));
             userRegistZymSingleCountDownView.setBackgroundResource(R.drawable.box_gray_white_bg);
             userRegistZymSingleCountDownView.setText(getResources().getString(R.string.user_requery_yzm));
         }
    }
    /**
     * 控制popu显示
     */
    public void showPopuWindow(){
        CustomPopupWindow customPopupWindow = new CustomPopupWindow.Builder().contentView(CustomPopupWindow.inflateView(this, R.layout.user_popuwindow_view)).parentView(userPhoneAttributionTxt).backgroundDrawable(getResources().getDrawable(R.drawable.button_white_bg))
                .animationStyle(R.style.mypopwindow_anim_style).customListener(new CustomPopupWindow.CustomPopupWindowListener() {
                    @Override
                    public void initPopupView(View contentView) {

                    }
                }).isWrap(true).isHaveBackGround(true).build();
        View view1 = customPopupWindow.getContentView();
        TextView user_popuwindow_view_flb = view1.findViewById(R.id.user_popuwindow_view_flb);
        TextView user_popuwindow_view_zg = view1.findViewById(R.id.user_popuwindow_view_zg);
        user_popuwindow_view_flb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                userPhoneAttributionTxt.setText("+63");
                customPopupWindow.dismiss();
            }
        });
        user_popuwindow_view_zg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                userPhoneAttributionTxt.setText("+86");
                customPopupWindow.dismiss();
            }
        });
        customPopupWindow.show();
    }
    @Override
    public void queryVerificationSuccess(VerificationBean verificationBean) {
        userPwdTxt.setText(verificationBean.getCode());
        isTimefinish=false;
        // 开启倒计时
        userRegistZymSingleCountDownView.setTime(60)
                .setTimeColorHex("#191919")
//                        .setTimePrefixText("前缀")
                .setTimeSuffixText("s")
                .startCountDown();
    }

    @Override
    public void registerNextSuccess() {
        //验证码校验成功跳转到下一个界面
        intent.putExtra("type","setPwd");
        intent.putExtra("identifyCode",userPwdTxt.getText().toString().trim());
        ArmsUtils.startActivityForResult(intent,AppConstant.START_ACTIVITY_REQUEST_CODE);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (userRegistZymSingleCountDownView!=null)
        {
            userRegistZymSingleCountDownView.pauseCountDown();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data!=null&&requestCode==AppConstant.START_ACTIVITY_REQUEST_CODE&&resultCode==RESULT_OK){
            //需要结束当前界面，回到登录界面
            killMyself();

        }
    }

    /**
     * h5投篮验证
     * @param activity
     * @param view
     */
    public void showCheackDialog(Activity activity,View view)
    {
        CustomPopupWindow dialog=new CustomPopupWindow.Builder().contentView(CustomPopupWindow.inflateView(activity, R.layout.user_login_cheak_dialog)).parentView(view)
                .animationStyle(R.style.mypopwindow_anim_style).customListener(new CustomPopupWindow.CustomPopupWindowListener() {
                    @Override
                    public void initPopupView(View contentView) {

                    }
                }).isHaveBackGround(true).isWrap(true).build();
        View view2 = dialog.getContentView();
        ImageView user_login_cheak_dialog_img=view2.findViewById(R.id.user_login_cheak_dialog_img);
        user_login_cheak_dialog_img.setImageResource(R.drawable.login_cheak_img);
        initView(view2, new WebViewCheakInterface() {
            @Override
            public void callBack(String data) {
                H5CheckCodeBean h5CheckCodeBean= null;
                try {
                    h5CheckCodeBean = new Gson().fromJson(data, H5CheckCodeBean.class);
                    Map<String,Object> maps=new HashMap<>();
                    if (userPhoneAttributionTxt.getText().toString().equals("+63"))
                    {
//                mPresenter.queryVerification("63"+userPhoneTxt.getText().toString(),sessionid,AppConstant.ALIYUNDUN_CHECK_APPID);
                        maps.put("phoneNum","63"+userPhoneTxt.getText().toString());
                    }else
                    {
//                mPresenter.queryVerification("86"+userPhoneTxt.getText().toString(),sessionid,AppConstant.ALIYUNDUN_CHECK_APPID);
                        maps.put("phoneNum","86"+userPhoneTxt.getText().toString());
                    }
                    maps.put("appKey",h5CheckCodeBean.getAppkey());
                    maps.put("scene",h5CheckCodeBean.getScene());
                    maps.put("sessionId",h5CheckCodeBean.getSessionid());
                    maps.put("sig",h5CheckCodeBean.getSig());
                    maps.put("token",h5CheckCodeBean.getNc_token());
                    mPresenter.message_new(maps);
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                    ArmsUtils.makeText(UserRegistActivity.this,"校验失败");
                }

                view2.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                       //两秒后关闭弹框
                        dialog.dismiss();

                    }
                },2000);
            }
        });
        dialog.show();
    }
    private void initView(View view, WebViewCheakInterface webViewCheakInterface) {
        // 页面布局。
        WebView testWebview = (WebView) view.findViewById(R.id.user_login_cheak_dialog_WebView);
        // 设置屏幕自适应。
        testWebview.getSettings().setUseWideViewPort(true);
        testWebview.getSettings().setLoadWithOverviewMode(true);
        // 建议禁止缓存加载，以确保在攻击发生时可快速获取最新的滑动验证组件进行对抗。
        testWebview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        // 设置不使用默认浏览器，而直接使用WebView组件加载页面。
        testWebview.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        // 设置WebView组件支持加载JavaScript。
        testWebview.getSettings().setJavaScriptEnabled(true);
        // 建立JavaScript调用Java接口的桥梁。
        testWebview.addJavascriptInterface(new testJsInterface(webViewCheakInterface), "testInterface");
        // 加载业务页面。
        testWebview.loadUrl(Api.url_h5_check);
    }
    public class testJsInterface {
        WebViewCheakInterface webViewCheakInterface;
        public testJsInterface( WebViewCheakInterface mwebViewCheakInterface){
            webViewCheakInterface=mwebViewCheakInterface;
        }
        @JavascriptInterface
        public void getSlideData(String callData) {
            System.out.println(callData);
            Log.i("#####",callData);
            webViewCheakInterface.callBack(callData);
        }
    }
}
